/**
 * 1038. 从二叉搜索树到更大和树（与 538 同）
 * https://leetcode-cn.com/problems/binary-search-tree-to-greater-sum-tree/
 */
public class Solutions_1038 {
    public static void main(String[] args) {
//        TreeNode root = new TreeNode(5);
//        root.left = new TreeNode(2);
//        root.right = new TreeNode(13);  // output: {18, 20, 13}

        TreeNode root = new TreeNode(4);
        root.left = new TreeNode(1);
        root.left.left = new TreeNode(0);
        root.left.right = new TreeNode(2);
        root.left.right.right = new TreeNode(3);
        root.right = new TreeNode(6);
        root.right.left = new TreeNode(5);
        root.right.right = new TreeNode(7);
        root.right.right.right = new TreeNode(8);
        // output: {30, 36, 21, 36, 35, 26, 15, null, null, null, 33, null, null, null, 8}

        TreeNode result = bstToGst(root);
        System.out.println(result);
    }

    // 累加和
    private static int sum = 0;

    public static TreeNode bstToGst(TreeNode root) {
        if (root != null) {
            // 中序遍历(右中左顺序)
            bstToGst(root.right);
            root.val += sum;
            sum = root.val;
            bstToGst(root.left);
        }
        return root;
    }
}
